package com.mjfeed.controller.shop.member;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mjfeed.controller.BaseController;
import com.mjfeed.entity.Area;
import com.mjfeed.entity.Cart;
import com.mjfeed.entity.Member;
import com.mjfeed.entity.Order;
import com.mjfeed.entity.PaymentMethod;
import com.mjfeed.entity.Receiver;
import com.mjfeed.entity.ShippingMethod;
import com.mjfeed.service.AreaService;
import com.mjfeed.service.CartItemService;
import com.mjfeed.service.CartService;
import com.mjfeed.service.MemberService;
import com.mjfeed.service.OrderService;
import com.mjfeed.service.PaymentMethodService;
import com.mjfeed.service.ProductCategoryService;
import com.mjfeed.service.ProductService;
import com.mjfeed.service.ReceiverService;
import com.mjfeed.service.ShippingMethodService;
import com.mjfeed.util.Format;
import com.mjfeed.util.Pagination;
import com.mjfeed.util.ParamBean;

/**
 * @description 订单
 * @author zhaominglei
 * @date 2014年10月8日
 */
@Controller("shopMemberOrderController")
@RequestMapping("/member/order")
public class OrderController extends BaseController {
	@Resource(name="memberService")
	private MemberService memberService;
	@Resource(name="productService")
	private ProductService productService;
	@Resource(name="productCategoryService")
	private ProductCategoryService productCategoryService;
	@Resource(name="cartService")
	private CartService cartService;
	@Resource(name="cartItemService")
	private CartItemService cartItemService;
	@Resource(name="orderService")
	private OrderService orderService;
	@Resource(name="paymentMethodService")
	private PaymentMethodService paymentMethodService;
	@Resource(name="shippingMethodService")
	private ShippingMethodService shippingMethodService;
	@Resource(name="receiverService")
	private ReceiverService receiverService;
	@Resource(name="areaService")
	private AreaService areaService;
	
	@RequestMapping(value = "/list" ,method=RequestMethod.GET)
	public String list(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response, Model model){
		Member member = memberService.getCurrent();
		if (member == null || member.getId() == null || member.getId() < 1) {
			return ERROR_VIEW;
		}
		paramBean.setUrl(getBasePath(request) + "member/order/list.shtml");
		int p = (Format.null2Zero(request.getParameter("p")) == 0) ? 1 : Format.null2Zero(request.getParameter("p"));
		paramBean.setPage(p);
		Pagination<Order> pagination = orderService.getPagination(paramBean, member);
		request.setAttribute("pagination", pagination);
		request.setAttribute("notPayCount", orderService.getNotPayCount(member));
		request.setAttribute("notShipCount", orderService.getNotShipCount(member));
		request.setAttribute("notReceiveCount", orderService.getNotReceiveCount(member));
		request.setAttribute("paramBean", paramBean);
		return "shop/member/order/list";
	}
	
	@RequestMapping(value = "/view" ,method=RequestMethod.GET)
	public String view(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("order", orderService.getById(Order.class, id));
		return "shop/member/order/view";
	}
	
	@RequestMapping(value = "/cancel", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> cancel(Long id, HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, Object> data = new HashMap<String, Object>();
		if (id == null || id < 1) {
			data.put("success", "false");
			data.put("message", "param error");
			return data;
		}
		Order pOrder = orderService.getById(Order.class, id);
		if (pOrder == null) {
			data.put("success", "false");
			data.put("message", "order not exists");
			return data;
		}
		pOrder.setOrderStatus(3);
		orderService.update(pOrder);
		data.put("success", "true");
		data.put("message", "success");
		return data;
	}
	
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public String info(HttpServletRequest request, HttpServletResponse response, Model model) {
		Cart cart = cartService.getCurrent();
		if (cart == null || cart.isEmpty()) {
			return "redirect:/cart/list.shtml";
		}
		Order order = orderService.build(cart, null, null, null, false, null, null);
		model.addAttribute("order", order);
		model.addAttribute("cartToken", cart.getToken());
		model.addAttribute("paymentMethods", paymentMethodService.getAll(PaymentMethod.class));
		model.addAttribute("shippingMethods", shippingMethodService.getAll(ShippingMethod.class));
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		return "/shop/member/order/info";
	}
	
	@RequestMapping(value = "/receiver/save", method=RequestMethod.POST)
	public String receiverSave(Receiver receiver, HttpServletRequest request, HttpServletResponse response, Model model){
		Member member = memberService.getCurrent();
		if (member == null || member.getId() == null || member.getId() < 1) {
			return ERROR_VIEW;
		}
		String areaId = request.getParameter("areaId");
		if (StringUtils.isEmpty(areaId)) {
			return ERROR_VIEW;
		}
		receiver.setIsDefault((receiver.getIsDefault() != null && receiver.getIsDefault()) ? true : false);
		receiver.setMember(member);
		receiver.setArea(areaService.getById(Area.class, Long.valueOf(areaId)));
		receiverService.save(receiver);
		return "redirect:/member/order/info.shtml";
	}
	
	@RequestMapping(value = "/create", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> create(String cartToken, Long receiverId, Long paymentMethodId, Long shippingMethodId, @RequestParam(defaultValue = "false") Boolean isInvoice, String invoiceTitle, String memo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, Object> data = new HashMap<String, Object>();
		Cart cart = cartService.getCurrent();
		if (cart == null || cart.isEmpty()) {
			data.put("success", "false");
			data.put("message", "cart isempty");
			return data;
		}
		if (!StringUtils.equals(cart.getToken(), cartToken)) {
			data.put("success", "false");
			data.put("message", "cart haschanged");
			return data;
		}
		if (cart.getIsLowStock()) {
			data.put("success", "false");
			data.put("message", "cart lowstock");
			return data;
		}
		Receiver receiver = receiverService.getById(Receiver.class, receiverId);
		if (receiver == null) {
			data.put("success", "false");
			data.put("message", "receiver notexsit");
			return data;
		}
		PaymentMethod paymentMethod = paymentMethodService.getById(PaymentMethod.class, paymentMethodId);
		if (paymentMethod == null) {
			data.put("success", "false");
			data.put("message", "paymentMethod notexsit");
			return data;
		}
		ShippingMethod shippingMethod = shippingMethodService.getById(ShippingMethod.class, shippingMethodId);
		if (shippingMethod == null) {
			data.put("success", "false");
			data.put("message", "shippingMethod notexsit");
			return data;
		}
		if (!paymentMethod.getShippingMethods().contains(shippingMethod)) {
			data.put("success", "false");
			data.put("message", "delivery unsupported");
			return data;
		}
		Order order = orderService.create(cart, receiver, paymentMethod, shippingMethod, isInvoice, invoiceTitle, memo, null);
		data.put("success", "true");
		data.put("message", "success");
		data.put("id", order.getId());
		return data;
	}
	
	@RequestMapping(value = "/payment", method=RequestMethod.GET)
	public String payment(Long id, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (id == null || id < 1) {
			return ERROR_VIEW;
		}
		Order order = orderService.getById(Order.class, id);
		if (order == null || !memberService.getCurrent().equals(order.getMember()) || order.isExpired() || order.getPaymentMethod() == null) {
			return ERROR_VIEW;
		}
		request.setAttribute("order", order);
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		return "/shop/member/order/payment";
	}
}
